<?php
defined('__JF')
		or die('Direct access is not allowed');
/*
 * Created on 15.10.2008
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
class JF_URI
{
	private $sURI 		= "";

	private $aMatched 	= array();

	public function __construct($sURI)
	{
		$this->sURI = $sURI;
	}

	public function match($sPattern)
	{
		$isMatched		= false;
		$this->aMatched = array();
		$aRequestTokens = $this->getTokens($this->sURI);
		$aPatternTokens = $this->getTokens($sPattern);
		if ((count($aRequestTokens) == 0) && (count($aPatternTokens) == 0)) {
			$isMatched = ($this->sURI == $sPattern);
		}
		else if (count($aRequestTokens) == count($aPatternTokens)) {
			for ($i = 0; $i < count($aRequestTokens); $i++) {
				if ($this->isVar($aPatternTokens[$i])) {
					$aVar = $this->parseVarParams($aPatternTokens[$i]);
					if ($aVar["type"] == JF_URIParamUtil::detectType($aRequestTokens[$i])) {
						if (($aVar["length"] == 0) || ($aVar["length"] == strlen($aRequestTokens[$i]))) {
							$this->aMatched[$aVar["name"]] = JF_URIParamUtil::getValue(
									$aVar["type"],
									$aRequestTokens[$i]
									);
							$isMatched = true;
						}
						else {
							$isMatched = false;
							break;
						}

					}
					else {
						$isMatched = false;
						break;
					}

				}
				else {
					$isMatched = ($aRequestTokens[$i] == $aPatternTokens[$i]);
					if (!$isMatched) {
						break;
					}
				}

			}

		}

		return $isMatched;
	}

	public function getURI()
	{
		return $this->sURI;
	}

	public function getMatched()
	{
		return $this->aMatched;
	}

	private function getTokens($sURI)
	{
		$aTokens = explode("/", $sURI);
		if (empty($aTokens[count($aTokens) - 1])) {
			unset($aTokens[count($aTokens) - 1]);
		}

		array_shift($aTokens);
		return (array) $aTokens;
	}

	private function isVar($sValue)
	{
		return ($sValue[0] == "{");
	}

	private function parseVarParams($sValue)
	{
		$sValue = str_replace(" ", "", $sValue);
		$sValue = substr($sValue, 1, (strlen($sValue) - 2));
		$aTemp1	= explode("=", $sValue);
		$aTemp2 = explode(":", $aTemp1[1]);
		if (!isset($aTemp2[1])) {
			$aTemp2[1] = 0;
		}

		return array(
				"name" 		=> $aTemp1[0],
				"type"		=> $aTemp2[0],
				"length"	=> $aTemp2[1]
				);
	}

}